<template>
  <div class="echart-line-wrapper" :style="containerStyle">
    <v-chart ref="chartRef" :option="chartOption" :style="chartStyle" autoresize />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
} from 'echarts/components';
import VChart from 'vue-echarts';
import { useAutoDataBinding } from '@/composables/use-data-binding';
import type { IDataBindingConfig } from '@/components/mt-edit/store/types';
import { shallowEqual, shouldUpdateChartData } from '@/utils/shallow-equal';

// 注册ECharts组件
use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
]);

// Props定义
interface Props {
  title?: string;
  backgroundColor?: string;
  xAxisData?: string[];
  seriesData?: number[];
  lineColor?: string;
  lineWidth?: number;
  showDataZoom?: boolean;
  smooth?: boolean;
  dataBinding?: IDataBindingConfig;
}

const props = withDefaults(defineProps<Props>(), {
  title: '折线图',
  backgroundColor: 'transparent',
  xAxisData: () => [],
  seriesData: () => [],
  lineColor: '#409EFF',
  lineWidth: 2,
  showDataZoom: false,
  smooth: false
});

const chartRef = ref();

// 响应式属性对象（用于数据绑定）
const componentProps = ref({
  title: props.title,
  backgroundColor: props.backgroundColor,
  xAxisData: [...props.xAxisData],
  seriesData: [...props.seriesData],
  lineColor: props.lineColor,
  lineWidth: props.lineWidth,
  smooth: props.smooth,
  showDataZoom: props.showDataZoom
});

// 使用数据绑定（hide属性由render-core处理，组件跳过）
const shouldUseDataBinding =
  props.dataBinding && props.dataBinding.enabled && props.dataBinding.targetProperty !== 'hide';

const dataBinding = useAutoDataBinding(
  shouldUseDataBinding ? props.dataBinding : null,
  componentProps.value,
  (property: string, value: any) => {
    // 直接更新响应式对象的属性
    if (componentProps.value.hasOwnProperty(property)) {
      (componentProps.value as any)[property] = value;
    }
  }
);

// 数据更新已由数据绑定composable处理，这里只需要直接更新属性

// 监听props变化，同步到响应式属性对象（应用浅比较优化）
watch(
  () => props.xAxisData,
  (newValue, oldValue) => {
    if (!shouldUseDataBinding || props.dataBinding?.targetProperty !== 'xAxisData') {
      // 使用浅比较优化，避免不必要的更新
      if (shouldUpdateChartData(newValue, oldValue)) {
        componentProps.value.xAxisData = [...newValue];
      }
    }
  },
  { deep: false } // 关闭深度监听，依赖浅比较
);

watch(
  () => props.seriesData,
  (newValue, oldValue) => {
    if (!shouldUseDataBinding || props.dataBinding?.targetProperty !== 'seriesData') {
      // 使用浅比较优化，避免不必要的更新
      if (shouldUpdateChartData(newValue, oldValue)) {
        componentProps.value.seriesData = [...newValue];
      }
    }
  },
  { deep: false } // 关闭深度监听，依赖浅比较
);

// 监听其他属性变化（应用浅比较优化）
watch(
  () => props.title,
  (newValue, oldValue) => {
    if (!shouldUseDataBinding || props.dataBinding?.targetProperty !== 'title') {
      // 字符串类型直接比较即可
      if (newValue !== oldValue) {
        componentProps.value.title = newValue;
      }
    }
  }
);

watch(
  () => props.lineColor,
  (newValue, oldValue) => {
    if (!shouldUseDataBinding || props.dataBinding?.targetProperty !== 'lineColor') {
      // 字符串类型直接比较即可
      if (newValue !== oldValue) {
        componentProps.value.lineColor = newValue;
      }
    }
  }
);

watch(
  () => props.backgroundColor,
  (newValue, oldValue) => {
    if (!shouldUseDataBinding || props.dataBinding?.targetProperty !== 'backgroundColor') {
      // 字符串类型直接比较即可
      if (newValue !== oldValue) {
        componentProps.value.backgroundColor = newValue;
      }
    }
  }
);

// 容器样式
const containerStyle = computed(() => ({
  width: '100%',
  height: '100%',
  backgroundColor: componentProps.value.backgroundColor
}));

// 图表样式
const chartStyle = computed(() => ({
  width: '100%',
  height: '100%'
}));

// ECharts配置
const chartOption = computed(() => ({
  title: {
    text: componentProps.value.title,
    left: 'center',
    textStyle: {
      fontSize: 16,
      color: '#333'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  legend: {
    bottom: 10,
    data: ['数据']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: props.showDataZoom ? '15%' : '10%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data:
      componentProps.value.xAxisData.length > 0
        ? componentProps.value.xAxisData
        : componentProps.value.seriesData.map((_, index) => `点${index + 1}`)
  },
  yAxis: {
    type: 'value'
  },
  dataZoom: props.showDataZoom
    ? [
        {
          type: 'inside',
          start: 0,
          end: 100
        },
        {
          start: 0,
          end: 100,
          height: 30
        }
      ]
    : undefined,
  series: [
    {
      name: '数据',
      type: 'line',
      smooth: props.smooth,
      itemStyle: {
        color: componentProps.value.lineColor
      },
      lineStyle: {
        color: componentProps.value.lineColor,
        width: componentProps.value.lineWidth
      },
      data: componentProps.value.seriesData
    }
  ]
}));

// 监听props变化，同步到响应式属性对象
watch(
  () => props.title,
  (newValue) => {
    if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'title') {
      componentProps.value.title = newValue;
    }
  }
);

watch(
  () => props.xAxisData,
  (newValue) => {
    if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'xAxisData') {
      componentProps.value.xAxisData = [...newValue];
    }
  },
  { deep: true }
);

watch(
  () => props.seriesData,
  (newValue) => {
    if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'seriesData') {
      componentProps.value.seriesData = [...newValue];
    }
  },
  { deep: true }
);

watch(
  () => props.lineColor,
  (newValue) => {
    if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'lineColor') {
      componentProps.value.lineColor = newValue;
    }
  }
);

watch(
  () => props.lineWidth,
  (newValue) => {
    if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'lineWidth') {
      componentProps.value.lineWidth = newValue;
    }
  }
);

watch(
  () => props.backgroundColor,
  (newValue) => {
    if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'backgroundColor') {
      componentProps.value.backgroundColor = newValue;
    }
  }
);

// 提供图表实例方法
const getChartInstance = () => {
  return chartRef.value?.getEchartsInstance();
};

defineExpose({
  getChartInstance,
  componentProps
});
</script>

<style scoped>
.echart-line-wrapper {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}
</style>
